from django.shortcuts import render
from rest_framework.views import APIView
from django.conf import settings
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from QQLoginTool.QQtool import OAuthQQ

import requests

# Create your views here.
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer


class OauthQQ_URLView(APIView):
    """
        构建qq登录跳转连接
    """

    def get(self, request):
        # 1、获取next值赋值给state
        state = request.query_params.get('next')
        # 2、如果获取不到next  手动给state指定一个值
        if state is None:
            state = '/'

        # 3、借助qqSDK创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 4、使用qq对象中的get_qq_url()方法生成跳转链接
        login_url = qq.get_qq_url()

        # 5、返回qq登录的跳转链接
        return Response({'login_url': login_url})


class OauthQQView(CreateAPIView):
    """
        获取openid和保存绑定oepnid
    """
    serializer_class = OauthSerializer

    def get(self, request):
        # 1、后端获取到code值请求qq服务器获取access_token值
        code = request.query_params.get('code')
        # 2、判断code值是否能够获取到
        if code is None:
            return Response({"errors": '缺少code值'}, status=403)

        # 3、借助qqSDK创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='/')

        access_token = qq.get_access_token(code)
        # 借助requests模块给qq服务器发送请求
        # data={
        #     'grant_type':'authorization_code',
        #     'client_id' : settings.QQ_CLIENT_ID,
        #     'client_secret' :settings.QQ_CLIENT_SECRET,
        #     'code' :code,
        #     'redirect_uri':settings.QQ_REDIRECT_URI
        #
        # }
        # r=requests.get('https://graph.qq.com/oauth2.0/token',params=data)
        # r.text

        # 4、获取到access_token值请求qq服务器获取openid值
        open_id = qq.get_open_id(access_token)

        # 5、判断openid是否绑定
        try:
            qq = OAuthQQUser.objects.get(openid=open_id)
        except:
            # 未绑定
            # 加密openid
            tjs = TJS(settings.SECRET_KEY, 300)
            openid = tjs.dumps({'open_id': open_id}).decode()

            return Response({'access_token': openid})

        else:
            # 已经绑定
            user = qq.user

            # 生成JWT token值
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response(
                {
                    'user_id': user.id,
                    'username': user.username,
                    'token': token
                }
            )

            # 合并购物车
            response = merge_cart_cookie_to_redis(request, response,user)

            return response
